package com.sgl.config;

import com.sgl.support.MyException;
import lombok.Data;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片服务器的客户端 生成类 以及初始化配置类
 */

@Data
public class FastDFSClient {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;




    //客户端加载fdfs的配置
    private void  initFdfsConfig(){
        try {
            ClientGlobal.initByProperties("fastdfs‐client.properties");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public FastDFSClient() throws Exception {
		/*if (conf.contains("classpath:")) {
			String path = URLDecoder.decode(getClass().getProtectionDomain().getCodeSource().getLocation().toString(),
					"UTF-8");
			path = path.substring(6);
			conf = conf.replace("classpath:", URLDecoder.decode(path, "UTF-8"));
			//conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
		}*/
        this.initFdfsConfig();
        //创建客户端
        trackerClient = new TrackerClient();
        //获取trackerServer
        trackerServer = trackerClient.getConnection();
        //获取storage
        storageServer = trackerClient.getStoreStorage(trackerServer);
        //获取storage client
        storageClient = new StorageClient1(trackerServer, storageServer);
    }

    /**
     * 上传文件方法
     * <p>
     * Title: uploadFile
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param fileName
     *            文件全路径
     * @param extName
     *            文件扩展名，不包含（.）
     * @param metas
     *            文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
        String result = storageClient.upload_file1(fileName, extName, metas);
        return result;
    }

    public String uploadFile(String fileName) throws Exception {
        return uploadFile(fileName, null, null);
    }

    public String uploadFile(String fileName, String extName) throws Exception {
        return uploadFile(fileName, extName, null);
    }

    /**
     * 上传文件方法
     * <p>
     * Title: uploadFile
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param fileContent
     *            文件的内容，字节数组
     * @param extName
     *            文件扩展名
     * @param metas
     *            文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {

        String result = storageClient.upload_file1(fileContent, extName, metas);
        return result;
    }

    public String uploadFile(byte[] fileContent) throws Exception {
        return uploadFile(fileContent, null, null);
    }

    public String uploadFile(byte[] fileContent, String extName) throws Exception {
        return uploadFile(fileContent, extName, null);
    }



    /**
     * 文件下载到磁盘
     * @param path 图片路径
     * @param output 输出流 中包含要输出到磁盘的路径
     * @return -1失败,0成功
     */
    public int download_file(String path, BufferedOutputStream output) {
        //byte[] b = storageClient.download_file(group, path);
        int result=-1;
        try {
            byte[] b = storageClient.download_file1(path);
            try{
                if(b != null){
                    output.write(b);
                    result=0;
                }
            }catch (Exception e){} //用户可能取消了下载
            finally {
                if (output != null)
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 获取文件数组
     * @param path 文件的路径 如group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public byte[] download_bytes(String path) {
        byte[] b=null;
        try {
            b = storageClient.download_file1(path);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }


    /**
     * 下载文件
     *
     * @param fileId
     *            文件ID（上传文件成功后返回的ID）
     *
     *
     * @return
     */
    public InputStream downloadFile(String fileId) {
        try {
            byte[] content = storageClient.download_file1(fileId);
            if (content != null) {
                InputStream input = new ByteArrayInputStream(content);
                return input;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }
}
